<template>
  <ul class="list">
    <li
      class="item" v-for="item of letters"
      :key="item"
      :ref="item"
      @touchstart.prevent="handleTouchStart"
      @touchmove="handleTouchMove"
      @touchend="handleTouchEnd"
      @click="handleLetterClick"
    >
      {{item}}
    </li>
  </ul>
</template>

<script>
export default {
  name: 'CityAlphabet',
  props: {
    cities: Object
  },
  computed: {
    letters () {
      const letters = []
      for (let i in this.cities) {
        letters.push(i)
      }
      return letters
    }
  },
  data () {
    return {
      touchStatus: false, // 设置手指触摸标识
      startY: 0, // 设置全局变量提升性能
      timer: null // 设置函数节流提升性能
    }
  },
  updated () {
    this.startY = this.$refs['A'][0].offsetTop
  },
  methods: {
    handleLetterClick (e) {
      this.$emit('change', e.target.innerText)
    },
    handleTouchStart () {
      this.touchStatus = true
    },
    handleTouchMove (e) {
      if (this.touchStatus) {
        if (this.timer) {
          clearTimeout()
        }
        this.timer = setTimeout(() => {
          const touchY = e.touches[0].clientY - 79 // 当前点击的高度
          const index = Math.floor((touchY - this.startY) / 20) // 当前点击的字母的序号
          // console.log(index)
          if (index >= 0 && index <= this.letters.length) {
            this.$emit('change', this.letters[index])
          }
        }, 16) // 设置16ms的延迟，防止频繁的请求
      }
    },
    handleTouchEnd () {
      this.touchStatus = false
    }
  }
}
</script>

<style lang="stylus" scoped>
  @import "~styles/varibles.styl"
  .list{
    position absolute
    width .4rem
    top $headerHeight+$searchHeight
    right 0
    bottom 0
    border-radius .5rem
    // 垂直居中
    display flex
    flex-direction column
    justify-content center
    .item{
      line-height .4rem
      text-align center
      color $bgColor
    }
  }
</style>
